package com.guodi.model.utils;

import java.io.*;
import java.util.UUID;

/**
 * @描述：用于调用生成Echart图片
 * @作者: 戴伙进
 * @日期: 2020/10/27 12:08
 */
public class EchartGenerateUtil {

    public static String generateEChart(String options) {
        String dataPath = writeFile(options);
        String fileName = "test-" + UUID.randomUUID().toString().substring(0, 8) + ".png";
        File tempFile = new File(FileUtil.tempFilePath);
        String path = tempFile.getAbsolutePath() + File.separator + fileName;
        try {
            File file = new File(path);     //文件路径（路径+文件名）
            if (!file.exists()) {   //文件不存在则创建文件，先创建目录
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            File phantomjsFile = new File(FileUtil.phantomjsPath);
            String cmd;
            if (phantomjsFile.exists()) {
                cmd = FileUtil.phantomjsPath + " " + FileUtil.jsPath + " -infile " + dataPath + " -outfile " + path;
            } else {
                cmd = "phantomjs " + FileUtil.jsPath + " -infile " + dataPath + " -outfile " + path;
            }
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //删除文件
            FileUtil.deleteFile(dataPath);
            return path;
        }
    }

    public static String writeFile(String options) {
        File dataFile = new File(FileUtil.tempFilePath);
        String dataPath = dataFile.getAbsolutePath() + File.separator + "data" + UUID.randomUUID().toString().substring(0, 8) + ".json";
        try {
            /* 写入Txt文件 */
            File writename = new File(dataPath); // 相对路径，如果没有则要建立一个新的output.txt文件
            if (!writename.exists()) {   //文件不存在则创建文件，先创建目录
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile(); // 创建新文件
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(options); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }
}
